﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Toolkit.Web.ViewComponents.DataGrid;
using Toolkit.Web.ViewComponents;
using Toolkit.Web.Infastructure;
using Toolkit.Web.ExtensionMethods;

namespace Toolkit.Web.Examples.DataGrid
{
    public partial class Index_Ajax : System.Web.UI.UserControl
    {
        private const string _persistenceKey = "datagridsettings-mvc3";

        public DataGridModel<Toolkit.Web.Examples.DataGrid.Index.GridEntry> Model
        {
            get;
            set;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.IsAjaxRequest() && Request["savePrefs"] == "True")
            {
                HandleSavePreferencesRequest();
            }
            else
            {
                HandleDataGridRequest();
            }
        }

        private void HandleDataGridRequest()
        {
            Model = GetModel(new DataGridInputModel(Request, null));

            if (!Request.IsAjaxRequest())
            {
                if (Request["delay"] == "True")
                {
                    Model.DataResults = null;
                }
            }
        }

        private void HandleSavePreferencesRequest()
        {
            // TODO
        }

        private DataGridModel<Toolkit.Web.Examples.DataGrid.Index.GridEntry> GetModel(DataGridInputModel input)
        {
            // Note: 'input' is never null due to mvc's defualt model binder.
            input.ApplyPersistentSettings(Request.Cookies[_persistenceKey]);

            // Default record set size if not set.
            if (!input.RecordSetSize.HasValue)
            {
                input.RecordSetSize = 500;
            }

            int total = (500 * 9) + 2;
            List<Toolkit.Web.Examples.DataGrid.Index.GridEntry> entries = new List<Toolkit.Web.Examples.DataGrid.Index.GridEntry>();

            for (int i = input.RecordStartIndex; i < Math.Min((input.RecordStartIndex + input.RecordSetSize.Value), total); i++)
            {
                entries.Add(new Toolkit.Web.Examples.DataGrid.Index.GridEntry(i));
            }

            DataGridModel<Toolkit.Web.Examples.DataGrid.Index.GridEntry> model = new DataGridModel<Toolkit.Web.Examples.DataGrid.Index.GridEntry>();
            model.DataResults = entries;
            model.InputModel = input;
            model.TotalNumberOfResults = total;
            model.PersistenceKey = _persistenceKey;

            return model;
        }
    }
}